<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"pengyz.com","root":"/","images":"/images","scheme":"Pisces","version":"8.7.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>
<meta name="description" content="RakNet简单介绍最近由于项目需要简单看了一下RakNet。这是一个C++开发的基于UDP的开源网络库，具有良好的跨平台特性，主要用于网络游戏的通信，也可以用在各种网络软件上用于处理网络通信。 总体来说这个库功能完善，提供可靠的UDP传输，完善的插件机制。项目托管在github目前已停止更新。关于它的具体用法，可以参考官网的例子和文档。">
<meta property="og:type" content="article">
<meta property="og:title" content="RakNet入门介绍">
<meta property="og:url" content="http://pengyz.com/2016/09/07/RakNet%E5%85%A5%E9%97%A8%E4%BB%8B%E7%BB%8D/index.html">
<meta property="og:site_name" content="Alex的技术博客">
<meta property="og:description" content="RakNet简单介绍最近由于项目需要简单看了一下RakNet。这是一个C++开发的基于UDP的开源网络库，具有良好的跨平台特性，主要用于网络游戏的通信，也可以用在各种网络软件上用于处理网络通信。 总体来说这个库功能完善，提供可靠的UDP传输，完善的插件机制。项目托管在github目前已停止更新。关于它的具体用法，可以参考官网的例子和文档。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2016-09-07T13:00:14.000Z">
<meta property="article:modified_time" content="2021-09-16T03:51:06.085Z">
<meta property="article:author" content="Alex Peng">
<meta property="article:tag" content="RakNet">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://pengyz.com/2016/09/07/RakNet%E5%85%A5%E9%97%A8%E4%BB%8B%E7%BB%8D/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://pengyz.com/2016/09/07/RakNet%E5%85%A5%E9%97%A8%E4%BB%8B%E7%BB%8D/","path":"2016/09/07/RakNet入门介绍/","title":"RakNet入门介绍"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>RakNet入门介绍 | Alex的技术博客</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="Alex的技术博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">Alex的技术博客</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">不忘初心，方得始终</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#RakNet%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8D"><span class="nav-number">1.</span> <span class="nav-text">RakNet简单介绍</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-overview">
            <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Alex Peng"
      src="/images/avata.png">
  <p class="site-author-name" itemprop="name">Alex Peng</p>
  <div class="site-description" itemprop="description">我的个人技术随笔</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">15</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/pengyz" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;pengyz" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:530948159@qq.com" title="E-Mail → mailto:530948159@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



          </div>
        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://pengyz.com/2016/09/07/RakNet%E5%85%A5%E9%97%A8%E4%BB%8B%E7%BB%8D/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avata.png">
      <meta itemprop="name" content="Alex Peng">
      <meta itemprop="description" content="我的个人技术随笔">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Alex的技术博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          RakNet入门介绍
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2016-09-07 21:00:14" itemprop="dateCreated datePublished" datetime="2016-09-07T21:00:14+08:00">2016-09-07</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-09-16 11:51:06" itemprop="dateModified" datetime="2021-09-16T11:51:06+08:00">2021-09-16</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E6%A1%A3/" itemprop="url" rel="index"><span itemprop="name">技术文档</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E6%A1%A3/socket/" itemprop="url" rel="index"><span itemprop="name">socket</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%8A%80%E6%9C%AF%E6%96%87%E6%A1%A3/socket/udp/" itemprop="url" rel="index"><span itemprop="name">udp</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="RakNet简单介绍"><a href="#RakNet简单介绍" class="headerlink" title="RakNet简单介绍"></a>RakNet简单介绍</h1><p>最近由于项目需要简单看了一下RakNet。<br>这是一个C++开发的基于UDP的开源网络库，具有良好的跨平台特性，主要用于网络游戏的通信，也可以用在各种网络软件上用于处理网络通信。</p>
<p>总体来说这个库功能完善，提供可靠的UDP传输，完善的插件机制。项目托管在<a target="_blank" rel="noopener" href="https://github.com/OculusVR/RakNet">github</a>目前已停止更新。关于它的具体用法，可以参考官网的例子和文档。</p>
<span id="more"></span>

<p>按照网上的说法 RakNet大概有如下特点：</p>
<blockquote>
<p>Radnet有以下特点：</p>
</blockquote>
<blockquote>
<pre><code>  高性能         在同一台计算机上，Radnet可以实现在两个程序之间每秒传输25，000条信息；
</code></pre>
</blockquote>
<blockquote>
<pre><code>  容易使用       Radnet有在线用户手册，视频教程。每一个函数和类都有详细的讲解，每一个功能都有自己的例程；
</code></pre>
</blockquote>
<blockquote>
<pre><code>  跨平台         当前Radnet支持Windows, Linux, Macs，可以建立在Visual Studio, GCC, Code: Blocks, DevCPP 和其它平台上；
</code></pre>
</blockquote>
<blockquote>
<pre><code>  在线技术支持   RakNet有一个活跃的论坛，邮件列表，你只要给他们发信，他们可以在几小时之内回复你。
</code></pre>
</blockquote>
<blockquote>
<pre><code>  安全的传输     RakNet在你的代码中自动使用SHA1, AES128, SYN，用RSA避免传输受到攻击
</code></pre>
</blockquote>
<blockquote>
<pre><code>  音频传输       用Speex编码解码，8位的音频只需要每秒500字节传输。
</code></pre>
</blockquote>
<blockquote>
<pre><code>  远程终端       用RakNet，你能远程管理你的程序，包括程序的设置，密码的管理和日志的管理。
</code></pre>
</blockquote>
<blockquote>
<pre><code>  目录服务器     目录服务器允许服务器列举他们自己需要的客户端，并与他们连接。
</code></pre>
</blockquote>
<blockquote>
<pre><code>  Autopatcher   Autopatcher系统将限制客户端传输到服务端的文件，这样是为了避免一些不合法的用户将一些不合法的文件传输到服务端。
</code></pre>
</blockquote>
<blockquote>
<pre><code>  对象重载系统
</code></pre>
</blockquote>
<blockquote>
<pre><code>  网络数据压缩   BitStream类允许压缩矢量，矩阵，四元数和在-1到1之间的实数。
</code></pre>
</blockquote>
<blockquote>
<pre><code>  远程功能调用
</code></pre>
</blockquote>
<blockquote>
<pre><code>  强健的通信层   可以保障信息按照不同的信道传输
</code></pre>
</blockquote>
<p>而且网上说这个东西的文档和例子丰富，然而百度了一圈发现，除了官网的例子，RakNet的其他例子很少。像我这样暂时只要一个UDP可靠通信的人来说，就有点不太友好了。百度知道上关于RakNet词条中的例子肯定不是4.x版本的，根本就不能用。<br>经过一番百度+测试，终于自己搞定了一个简单的例子，代码贴上来做个备忘。</p>
<p>VS2015的测试工程，新建控制台工程，把github上clone的src目录的源码全部添加到工程，然后加上如下的测试代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br></pre></td><td class="code"><pre><span class="line">#include &quot;../RakNet/src/RakPeerInterface.h&quot;</span><br><span class="line">#include &quot;../RakNet/src/RakNetTypes.h&quot;</span><br><span class="line">#include &quot;../RakNet/src/MessageIdentifiers.h&quot;</span><br><span class="line">#include &quot;../RakNet/src/BitStream.h&quot;</span><br><span class="line">#include &quot;../RakNet/src/RakString.h&quot;</span><br><span class="line">#include &quot;../RakNet/src/StringCompressor.h&quot;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">int StartServer();</span><br><span class="line">int StartClient(void* param);</span><br><span class="line"></span><br><span class="line">//测试下RakNet</span><br><span class="line">void main(int argc, char* argv[]) &#123;</span><br><span class="line">	PTHREAD pThread = 0;</span><br><span class="line">	RakNet::RakPeerInterface* peer = RakNet::RakPeerInterface::GetInstance();</span><br><span class="line">	if (!peer)</span><br><span class="line">	&#123;</span><br><span class="line">		LogUtils::e(LOG_TAG, &quot;main get peer failed.&quot;);</span><br><span class="line">		system(&quot;pause&quot;);</span><br><span class="line">		return;</span><br><span class="line">	&#125;</span><br><span class="line">	LogUtils::i(LOG_TAG, &quot;（C）客服端 (S)服务器?&quot;);</span><br><span class="line">	char str = getchar();</span><br><span class="line">	if (str == &#x27;c&#x27;)</span><br><span class="line">	&#123;</span><br><span class="line">		StartClient(NULL);</span><br><span class="line">		//PlatformAbstract::CreateThread(pThread, (THREADPROCTYPE)&amp;StartClient, NULL);</span><br><span class="line">		LogUtils::e(LOG_TAG, &quot;::main 客服端已经建立。&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	else</span><br><span class="line">	&#123;</span><br><span class="line">		StartServer();</span><br><span class="line">		//PlatformAbstract::CreateThread(pThread, (THREADPROCTYPE)&amp;StartServer, NULL);</span><br><span class="line">		LogUtils::e(LOG_TAG, &quot;::main 服务器已经建立。&quot;);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	system(&quot;pause&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">////这里是一个测试方法 可以直接放到测试工程中测试</span><br><span class="line">int StartServer() &#123;</span><br><span class="line">	//给服务器端创建一个实例  </span><br><span class="line">	RakNet::RakPeerInterface* pPeer = RakNet::RakPeerInterface::GetInstance();</span><br><span class="line">	if (NULL == pPeer)</span><br><span class="line">	&#123;</span><br><span class="line">		LogUtils::e(LOG_TAG, &quot;TestFunc get pPeer failed.&quot;);</span><br><span class="line">		return -1;</span><br><span class="line">	&#125;</span><br><span class="line">	else</span><br><span class="line">	&#123;</span><br><span class="line">		LogUtils::e(LOG_TAG, &quot;::TestFunc ---------MyChatServer Init Success(C)-----------&quot;);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	RakNet::Packet* pPacket;</span><br><span class="line">	LogUtils::i(LOG_TAG, &quot;::TestFunc Start Server .....&quot;);</span><br><span class="line">	//启动服务器  </span><br><span class="line">	RakNet::SocketDescriptor sd = RakNet::SocketDescriptor(6000, 0);</span><br><span class="line">	RakAssert(RakNet::RAKNET_STARTED == pPeer-&gt;Startup(1, &amp;sd, 1));</span><br><span class="line">	//设置最大链接数  </span><br><span class="line">	pPeer-&gt;SetMaximumIncomingConnections(1);</span><br><span class="line">	auto boundAddress = pPeer-&gt;GetMyBoundAddress();</span><br><span class="line">	const char* sAddr = boundAddress.ToString();</span><br><span class="line">	LogUtils::e(LOG_TAG, &quot;::StartServer sAddr: %s&quot;, sAddr);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	//////////////////////////////////////////////////////////////////////////  </span><br><span class="line">	while (1)</span><br><span class="line">	&#123;</span><br><span class="line">		for (pPacket = pPeer-&gt;Receive(); pPacket; pPeer-&gt;DeallocatePacket(pPacket), pPacket = pPeer-&gt;Receive())</span><br><span class="line">		&#123;</span><br><span class="line">			LogUtils::e(LOG_TAG, &quot;StartServer pPacket type: %d&quot;, pPacket-&gt;data[0]);</span><br><span class="line">			switch (pPacket-&gt;data[0])</span><br><span class="line">			&#123;</span><br><span class="line">			case ID_REMOTE_DISCONNECTION_NOTIFICATION: &#123;</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;StartServer Another client has disconnected&quot;);</span><br><span class="line">			&#125;break;</span><br><span class="line">			case ID_REMOTE_CONNECTION_LOST: &#123;</span><br><span class="line">				LogUtils::i(LOG_TAG, &quot;StartServer ID_REMOTE_CONNECTION_LOST&quot;);</span><br><span class="line">			&#125;break;</span><br><span class="line">			case ID_REMOTE_NEW_INCOMING_CONNECTION: &#123;</span><br><span class="line">				LogUtils::i(LOG_TAG, &quot;StartServer ID_REMOTE_CONNECTION_LOST&quot;);</span><br><span class="line">				RakNet::BitStream bs;</span><br><span class="line">				bs.Write &lt; RakNet::MessageID&gt;(ServerConnectBack);</span><br><span class="line">				RakNet::StringCompressor::Instance()-&gt;EncodeString(pPacket-&gt;systemAddress.ToString(true), 255, &amp;bs);</span><br><span class="line"></span><br><span class="line">			&#125;break;</span><br><span class="line">				//client端调用Connect后收到的server响应</span><br><span class="line">			case ID_CONNECTION_REQUEST_ACCEPTED: &#123;</span><br><span class="line">				LogUtils::i(LOG_TAG, &quot;StartServer ID_CONNECTION_REQUEST_ACCEPTED&quot;);</span><br><span class="line"></span><br><span class="line">				RakNet::BitStream bsOut;</span><br><span class="line">				bsOut.Write((RakNet::MessageID)ID_USER_PACKET_ENUM + 1);</span><br><span class="line">				bsOut.Write(&quot;Server Say Hello.&quot;);</span><br><span class="line">				pPeer-&gt;Send(&amp;bsOut, HIGH_PRIORITY, UNRELIABLE_SEQUENCED, 0, pPeer-&gt;GetMyBoundAddress(), false);</span><br><span class="line">			&#125;break;</span><br><span class="line">				//server端收到来自client的Connect</span><br><span class="line">			case ID_NEW_INCOMING_CONNECTION: &#123;</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;StartServer ID_NEW_INCOMING_CONNECTION&quot;);</span><br><span class="line">			&#125;break;</span><br><span class="line">			case ID_NO_FREE_INCOMING_CONNECTIONS: &#123;</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;StartServer ID_NO_FREE_INCOMING_CONNECTIONS&quot;);</span><br><span class="line">			&#125;break;</span><br><span class="line">			case ID_DISCONNECTION_NOTIFICATION: &#123;</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;StartServer ID_DISCONNECTION_NOTIFICATION&quot;);</span><br><span class="line">			&#125;break;</span><br><span class="line">			case ID_CONNECTION_LOST: &#123;</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;StartServer ID_CONNECTION_LOST&quot;);</span><br><span class="line">			&#125;break;</span><br><span class="line">			case ID_CONNECTION_ATTEMPT_FAILED: &#123;</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;StartServer ID_CONNECTION_ATTEMPT_FAILED&quot;);</span><br><span class="line">			&#125;break;</span><br><span class="line"></span><br><span class="line">				//用户自定义数据包  </span><br><span class="line">			case ID_USER_PACKET_ENUM + 1:</span><br><span class="line">			&#123;</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;StartServer recv ID_USER_PACKET_ENUM + 1: %d&quot;, ID_USER_PACKET_ENUM + 1);</span><br><span class="line">				RakNet::RakString rs1, rs2;</span><br><span class="line">				RakNet::BitStream bsIn(pPacket-&gt;data, pPacket-&gt;length, false);</span><br><span class="line">				bsIn.IgnoreBytes(sizeof(RakNet::MessageID));</span><br><span class="line">				//bsIn.Read(rs);  //提取字符串           </span><br><span class="line">				RakNet::StringCompressor::Instance()-&gt;DecodeString(&amp;rs1, 255, &amp;bsIn);</span><br><span class="line">				RakNet::StringCompressor::Instance()-&gt;DecodeString(&amp;rs2, 255, &amp;bsIn);</span><br><span class="line">				LogUtils::e(LOG_TAG, &quot;::StartServer Recv User Data: %s %s %s&quot;, pPacket-&gt;systemAddress.ToString(true, &#x27;|&#x27;), rs1.C_String(), rs2.C_String());</span><br><span class="line">			&#125;</span><br><span class="line">			break;</span><br><span class="line"></span><br><span class="line">			default: &#123;</span><br><span class="line">				LogUtils::i(LOG_TAG, &quot;::TestFunc Message with identifier %i has arrived&quot;, pPacket-&gt;data[0]);</span><br><span class="line">			&#125;break;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		sleep(100);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	//////////////////////////////////////////////////////////////////////////  </span><br><span class="line">	RakNet::RakPeerInterface::DestroyInstance(pPeer);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">int StartClient(void* param) &#123;</span><br><span class="line">	//获取RakNetPeer接口</span><br><span class="line">	RakNet::RakPeerInterface* peer = RakNet::RakPeerInterface::GetInstance();</span><br><span class="line">	if (!peer)</span><br><span class="line">	&#123;</span><br><span class="line">		LogUtils::e(LOG_TAG, &quot;::StartClient get peer failed.&quot;);</span><br><span class="line">		return 0;</span><br><span class="line">	&#125;</span><br><span class="line">	RakNet::SocketDescriptor  sd = RakNet::SocketDescriptor(0, 0);</span><br><span class="line">	RakAssert(RakNet::RAKNET_STARTED == peer-&gt;Startup(1, &amp;sd, 1));</span><br><span class="line">	LogUtils::i(LOG_TAG, &quot;::StartClient get peer success&quot;);</span><br><span class="line">	RakAssert(RakNet::CONNECTION_ATTEMPT_STARTED == peer-&gt;Connect(&quot;127.0.0.1&quot;, 6000, 0, 0, 0, 0));</span><br><span class="line">	while (peer-&gt;IsActive())</span><br><span class="line">	&#123;</span><br><span class="line">		//开始发包了</span><br><span class="line">		LogUtils::i(LOG_TAG, &quot;::StartClient %d 发包&quot;, GetTickCount());</span><br><span class="line"></span><br><span class="line">		RakNet::BitStream bIn;</span><br><span class="line">		bIn.Write&lt;RakNet::MessageID&gt;(ID_USER_PACKET_ENUM + 1);</span><br><span class="line">		RakNet::StringCompressor::Instance()-&gt;EncodeString(&quot;Client Say Hello&quot;, 255, &amp;bIn);</span><br><span class="line">		RakNet::StringCompressor::Instance()-&gt;EncodeString(&quot;Client Say NMH&quot;, 255, &amp;bIn);</span><br><span class="line">		//注意broadcast参数 如果是true，则发广播，systemidentifier表示不发送地址，一般使用常量 RakNet::UNASSIGNED_SYSTEM_ADDRESS</span><br><span class="line">		//					如果是false，则往systemidentifier指定的ip和端口处发送</span><br><span class="line">		//					如果发包是有序的，则channel指定了信道，同一信道的具有递增的排序值，避免有多种有序消息的排序值相互干扰</span><br><span class="line">		uint32_t sendrs = peer-&gt;Send(&amp;bIn, HIGH_PRIORITY, UNRELIABLE_SEQUENCED, 0, RakNet::SystemAddress(&quot;127.0.0.1&quot;, 6000), false);</span><br><span class="line">		LogUtils::e(LOG_TAG, &quot;StartClient sendres: %d&quot;, sendrs);</span><br><span class="line">		Sleep(1000);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	peer-&gt;Shutdown(1000);</span><br><span class="line">	RakNet::RakPeerInterface::DestroyInstance(peer);</span><br><span class="line">	peer = NULL;</span><br><span class="line">	LogUtils::e(LOG_TAG, &quot;Disconnect from Server. StartClient peer closed&quot;);</span><br><span class="line">	return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>对于Android，我们可以把RakNet编译成静态库，然后链接到我们的so库中使用，</p>
<p>Android.mk内容如下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">LOCAL_PATH := $(call my-dir)</span><br><span class="line"></span><br><span class="line">include $(CLEAR_VARS)</span><br><span class="line">LOCAL_MODULE := RakNet</span><br><span class="line">LOCAL_MODULE_FILENAME := libRakNet</span><br><span class="line"></span><br><span class="line">APP_ABI := armeabi armeabi-v7a </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 遍历目录及子目录的函数</span><br><span class="line">define walk</span><br><span class="line">$(wildcard $(1)) $(foreach e, $(wildcard $(1)/*), $(call walk, $(e)))</span><br><span class="line">endef</span><br><span class="line"></span><br><span class="line"># 按目录引用</span><br><span class="line">FILE_LIST := $(filter %.cpp, $(call walk, $(LOCAL_PATH)/src))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 这里注意做一次重复条目过滤 call uniq 不然重复条目会报很多错误</span><br><span class="line">LOCAL_SRC_FILES := $(call uniq,$(FILE_LIST:$(LOCAL_PATH)/%=%))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">include $(BUILD_STATIC_LIBRARY)</span><br></pre></td></tr></table></figure>

<p>Application.mk内容如下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">APP_STL := gnustl_static</span><br><span class="line">APP_CPPFLAGS += -fexceptions</span><br><span class="line">APP_ABI :=armeabi armeabi-v7a</span><br><span class="line">APP_PLATFORM := android-19</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/RakNet/" rel="tag"># RakNet</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
            </div>
            <div class="post-nav-item">
                <a href="/2017/01/10/%E5%B0%8F%E8%AE%AE%E7%A8%8B%E5%BA%8F%E5%91%98%E7%9A%84%E8%87%AA%E6%88%91%E4%BF%AE%E5%85%BB/" rel="next" title="小议程序员的自我修养">
                  小议程序员的自我修养 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Alex Peng</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/third-party/search/local-search.js"></script>




  





</body>
</html>
